package com.fly.demo.service.impl;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.fly.demo.service.TokenService;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class TokenServiceGuavaImpl implements TokenService
{
    /**
     * 30分钟失效
     */
    Cache<String, String> cache = CacheBuilder.newBuilder().expireAfterWrite(30, TimeUnit.MINUTES).build();
    
    /**
     * 验证token是否合法
     * 
     * @param token
     */
    @Override
    public boolean valide(String token)
    {
        return StringUtils.equals(token, getToken());
    }
    
    /**
     * 获取sysToken
     */
    private String getToken()
    {
        String sysToken = cache.getIfPresent("token");
        if (sysToken == null)
        {
            sysToken = UUID.randomUUID().toString().replace("-", "");
            log.info("------ now valid sysToken is： {}", sysToken);
            cache.put("token", sysToken);
        }
        return sysToken;
    }
}
